//
//  PHElectricityViewController.m
//  PhnixHome
//
//  Created by Levy Xu on 2017/11/28.
//  Copyright © 2017年 Levy Xu. All rights reserved.
//

#import "PHElectricityViewController.h"
#import <PNChart/PNChart.h>
#import "PHProgressBar.h"

@interface PHElectricityViewController ()<PNChartDelegate>
@property(nonatomic, strong) PHDevice *model;
@property(nonatomic, strong) QMUIButton *electricityBtn;
@property(nonatomic, strong) QMUIGhostButton *weekBtn;
@property(nonatomic, strong) QMUIGhostButton *monthBtn;
@property(nonatomic, strong) PNLineChart *lineChart;
@property(nonatomic, strong) QMUIButton *moneyBtn;
@property(nonatomic, strong) PHProgressBar *totalMoneyBar;
@property(nonatomic, strong) PHProgressBar *saveMoneyBar;
@property(nonatomic, strong) QMUILabel *tipsLabel;
@property(nonatomic, strong) QMUIButton *tipsButton;
@property(nonatomic, strong) NSArray *elecArray;
@end

@implementation PHElectricityViewController

- (instancetype)initWithDeviceModel:(PHDevice *)model {
    self = [super init];
    if (self) {
        _model = model;
    }
    return self;
}

- (void)initSubviews {
    [super initSubviews];
    
    _electricityBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [_electricityBtn setImage:UIImageMake(@"icon_electricity") forState:UIControlStateNormal];
    [_electricityBtn setTitleColor:UIColorGray4 forState:UIControlStateNormal];
    [_electricityBtn setTitle:NSLocalizedString(@"electricity_consumption", nil) forState:UIControlStateNormal];
    _electricityBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    _electricityBtn.titleLabel.font = CodeFontMake(16);
    _electricityBtn.spacingBetweenImageAndTitle = 5.0f;
    [self.myView addSubview:_electricityBtn];
    
    _weekBtn = [[QMUIGhostButton alloc] initWithGhostType:QMUIGhostButtonColorRed];
    _weekBtn.titleLabel.font = CodeFontMake(16);
    [_weekBtn setTitle:NSLocalizedString(@"week", nil) forState:UIControlStateNormal];
    [_weekBtn addTarget:self action:@selector(weekAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.myView addSubview:_weekBtn];
    
    _monthBtn = [[QMUIGhostButton alloc] initWithGhostType:QMUIGhostButtonColorRed];
    _monthBtn.titleLabel.font = CodeFontMake(16);
    [_monthBtn setTitle:NSLocalizedString(@"month", nil) forState:UIControlStateNormal];
    [_monthBtn addTarget:self action:@selector(monthAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.myView addSubview:_monthBtn];
    
    CGFloat lineY = 60;
    CGFloat lineH = 200;
    if (IS_35INCH_SCREEN) {
        lineY = 40;
        lineH = 140;
    } else if (IS_40INCH_SCREEN) {
        lineH = 180;
    }
    
    _lineChart = [[PNLineChart alloc] initWithFrame:CGRectMake(5, lineY, SCREEN_WIDTH - 30, lineH)];
    _lineChart.backgroundColor = [UIColor clearColor];
    _lineChart.showCoordinateAxis = YES;
    _lineChart.showYGridLines = YES;
    _lineChart.showSmoothLines = YES;
    _lineChart.xUnit = NSLocalizedString(@"day", nil);
    _lineChart.xLabelFont = CodeFontMake(10);
    _lineChart.xLabelColor = UIColorGray3;
    _lineChart.yLabelFont = CodeFontMake(14);
    _lineChart.yLabelColor = UIColorGray3;
    _lineChart.yLabelFormat = @"%.0f";
    _lineChart.yUnit = NSLocalizedString(@"degree", nil);
    [self.myView addSubview:_lineChart];
    
    _moneyBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [_moneyBtn setImage:UIImageMake(@"icon_money") forState:UIControlStateNormal];
    NSString *string = [NSString stringWithFormat:@"%@(%@)", NSLocalizedString(@"money_amount", nil), kMonths[[[NSDate date] month] - 1]];
    [_moneyBtn setTitle:string forState:UIControlStateNormal];
    [_moneyBtn setTitleColor:UIColorGray4 forState:UIControlStateNormal];
    _moneyBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    _moneyBtn.titleLabel.font = CodeFontMake(16);
    _moneyBtn.spacingBetweenImageAndTitle = 5.0f;
    [self.myView addSubview:_moneyBtn];
    
    _totalMoneyBar = [[PHProgressBar alloc] init];
    _totalMoneyBar.title = NSLocalizedString(@"money_cost", nil);
    [self.myView addSubview:_totalMoneyBar];
    
    _saveMoneyBar = [[PHProgressBar alloc] init];
    _saveMoneyBar.title = NSLocalizedString(@"money_save", nil);
    [self.myView addSubview:_saveMoneyBar];
    
    _tipsLabel = [[QMUILabel alloc] init];
    _tipsLabel.font = CodeFontMake(14);
    _tipsLabel.textColor = UIColorGray4;
    _tipsLabel.textAlignment = NSTextAlignmentLeft;
    _tipsLabel.numberOfLines = 0;
    [self.myView addSubview:_tipsLabel];
    
    UIImage *editImage = [UIImageMake(@"icon_edit") imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    _tipsButton = [QMUIButton buttonWithType:UIButtonTypeCustom];
    _tipsButton.adjustsButtonWhenHighlighted = YES;
    _tipsButton.imageEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);
    [_tipsButton setImage:editImage forState:UIControlStateNormal];
    [_tipsButton addTarget:self action:@selector(tipsAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.myView addSubview:_tipsButton];
}

- (void)viewDidLayoutSubviews {
    self.shouldShowMyView = YES;
    [super viewDidLayoutSubviews];
    
    CGFloat electY = 15;
    CGFloat moneyY = _lineChart.qmui_bottom + 20;
    CGFloat totalY = 30;
    CGFloat saveY = 30;
    CGFloat tipsB = self.myView.qmui_height - 20;
    if (SCREEN_HEIGHT == 480) {
        electY = 5;
        moneyY = _lineChart.qmui_bottom + 10;
        totalY = 10;
        saveY = 10;
        tipsB = self.myView.qmui_height - 10.0f;
    } else if (IS_40INCH_SCREEN) {
        totalY = 20;
        saveY = 20;
        tipsB = self.myView.qmui_height - 10.0f;
    }
    
    _electricityBtn.frame = CGRectMake(10, electY, 230, 30);
    _weekBtn.frame = CGRectMake(self.myView.qmui_width - 80, electY, 30, 30);
    _monthBtn.frame = CGRectMake(self.myView.qmui_width - 40, electY, 30, 30);
    
    _moneyBtn.frame = CGRectMake(10, moneyY, 230, 30);
    _totalMoneyBar.frame = CGRectMake(10, _moneyBtn.qmui_bottom + totalY, self.myView.qmui_width - 20, 20);
    _saveMoneyBar.frame = CGRectMake(10, _totalMoneyBar.qmui_bottom + saveY, _totalMoneyBar.qmui_width, _totalMoneyBar.qmui_height);
    
    _tipsLabel.frame = CGRectMake(10, self.myView.qmui_height - 80, self.myView.qmui_width - 50, 60);
    [_tipsLabel sizeToFit];
    _tipsLabel.qmui_bottom = tipsB;
    _tipsButton.frame = CGRectMake(_tipsLabel.qmui_right, _tipsLabel.qmui_bottom - 40, 40, 40);
    
    [self.myView bringSubviewToFront:_tipsButton];
}

-(void)weekAction:(id)sender {
    _weekBtn.ghostColor = GhostButtonColorRed;
    _monthBtn.ghostColor = GhostButtonColorGray;
    
    WS(ws);
    [_model getElectricityTwoMonth:^(BOOL success) {
        if (success) {
            ws.elecArray = [ws.model electricityForDays:7];
            
            [ws drawLineChart];
        }
    }];
}

-(void)monthAction:(id)sender {
    _weekBtn.ghostColor = GhostButtonColorGray;
    _monthBtn.ghostColor = GhostButtonColorRed;
    
    WS(ws);
    [_model getElectricityTwoMonth:^(BOOL success) {
        if (success) {
            ws.elecArray = [ws.model electricityForDays:30];
            
            [ws drawLineChart];
        }
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self weekAction:nil];
    
    [self refresh];
}

-(void)refresh {
    
    float price = [PHAnalysis getElectricityPrice];
    
    WS(ws);
    [_model getElectricityTwoMonth:^(BOOL success) {
        if (success) {
            float total = [ws.model totalElectThisMonth];
            ws.totalMoneyBar.progressBar.progress = total / 100;
            ws.totalMoneyBar.valueLabel.text = [NSString stringWithFormat:@"%.2f RMB", total * price];
            
            [ws.model getCOPThisMonth:^(BOOL success) {
                if (success) {
                    float saving = [ws.model totalElectSavedThisMonth];
                    ws.saveMoneyBar.progressBar.progress = saving / 400;
                    ws.saveMoneyBar.valueLabel.text = [NSString stringWithFormat:@"%.2f RMB", saving * price];
                }
            }];
        }
    }];
    
    _tipsLabel.text = [NSString stringWithFormat:NSLocalizedString(@"electricity_price_tips", nil), price];
}

-(void)drawLineChart {
    if (!_elecArray)
        return;
    
    float max = 0;
    NSMutableArray *xLabels = [NSMutableArray array];
    int xgap = (int)(_elecArray.count / 10) + 1;
    for (int i = 0; i < _elecArray.count; i++) {
        PHAnalysis *tmp = _elecArray[i];
        if (xgap == 1 || (xgap > 1 && i % xgap == 0)) {
            [xLabels addObject:[tmp.myDate stringWithFormat:@"M.d"]];
        } else {
            [xLabels addObject:@""];
        }
        if(tmp.value > max) {
            max = tmp.value;
        }
    }
    _lineChart.xLabels = xLabels;
    
    int gap = (int)(max / 5) + 1;
    _lineChart.yFixedValueMax = 5 * gap;
    _lineChart.yFixedValueMin = 0.0f;
    _lineChart.yLabelNum = 5;
    
    WS(ws);
    PNLineChartData *data1 = [PNLineChartData new];
    data1.color = PNFreshGreen;
    data1.alpha = 0.8f;
    data1.itemCount = _elecArray.count;
    data1.inflexionPointWidth = 4.0f;
    data1.inflexionPointColor = UIColorRed;
    data1.inflexionPointStyle = PNLineChartPointStyleCircle;
    data1.lineWidth = 2.0f;
    data1.getData = ^PNLineChartDataItem *(NSUInteger item) {
        PHAnalysis *analysis = ws.elecArray[item];
        return [PNLineChartDataItem dataItemWithY:analysis.value];
    };
    _lineChart.chartData = @[ data1 ];
    [_lineChart strokeChart];
}

-(void)tipsAction:(id)sender {
    WS(ws);
    NSString *text = [NSString stringWithFormat:@"%.03f",[PHAnalysis getElectricityPrice]];
    [KKAlert inputWithTitle:NSLocalizedString(@"electricity_price", nil) text:text placeholder:@"" ok:^(NSString *string) {
        float price = [string floatValue];
        [PHAnalysis saveElectricityPrice:price];
        [ws refresh];
    }];
}

- (void)setupNavigationItems {
    [super setupNavigationItems];
    self.title = NSLocalizedString(@"title_cost_statistics", nil);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
